'use strict';
// admin主内容头部导航
module.exports = (options, app) => {
  return async function navigateMiddleware(ctx, next) {
    const active_url = ctx.request.path;
    const url_arr = active_url.split('\/');
    // 判断是否为/admin/index/index路径格式
    if (url_arr.length === 4) {
      const Systemmodule = ctx.model.Systemmodule.getTableName('tableName');
      if (!ctx.model.Systemmodule.associations || !ctx.model.Systemmodule.associations.SysTo) {
        ctx.model.Systemmodule.hasOne(ctx.model.Systemmodule, { as: 'SysTo', foreignKey: 'mod_id' });
      }
      const data = await ctx.model.Systemmodule.find({
        where: {
          ctl: url_arr[2],
          act: url_arr[3],
        },
        attributes: ['mod_id', 'parent_id', 'level', 'title', [app.Sequelize.literal('SysTo.title'), 'p_title']],
        include: [
          {
            model: ctx.model.Systemmodule,
            as: 'SysTo',
            required: true, // true:内连接 false: 左外连接
            on: {
              mod_id: {
                [app.Sequelize.Op.eq]: app.Sequelize.col(`${Systemmodule}.parent_id`),
              },
            },
            attributes: [],
          },
        ],
        raw: true,
      });
      if (data && data.mod_id) {
        const navigate = [ '系统后台', data.p_title, data.title ];
        ctx.app.locals.navigate_admin = navigate;
      }
    }
    await next();
  };
};

